import React from "react";
import routeWithUserSession from "@/components/ApplicationArea/routeWithUserSession";
import PageHeader from "@/components/PageHeader";
import { BrowserRouter as Router,Link } from 'react-router-dom';//
import Layout from "antd/lib/layout";
import Button from "antd/lib/button";
import Col from "antd/lib/col";
import Divider from "antd/lib/divider";
import Form from "antd/lib/form";
import Input from "antd/lib/input";
import Row from "antd/lib/row";
import Table from "antd/lib/table";
import ConfigProvider from "antd/lib/config-provider";
import Modal from "antd/lib/modal";
import Tree from "antd/lib/tree";
import zhCN from 'antd/es/locale/zh_CN';
import Workflow from "@/services/workflow";
import Tabletype from "@/services/tabletype";
import { currentUser } from "@/services/auth";
import {createBrowserHistory} from 'history'
import notification from "@/services/notification";
import {get} from "lodash";
import routes from "@/services/routes";
import {WarningOutlined,SecurityScanTwoTone,DownOutlined} from "@ant-design/icons";

const customHistory = createBrowserHistory();

const {Sider } = Layout;
const { confirm } = Modal;
class WorkFlowList extends React.Component {
  state = {
    page: 1,
    pagesize: localStorage.getItem("workflowlistpagesize") ? (localStorage.getItem("workflowlistpagesize") !== undefined ? Number(localStorage.getItem("workflowlistpagesize")) : 20) : 20,
    total:10,
    loading: false,
    name: '',
    data: [],
    gData: [],
    bill_enum: '',
    bill_type: '',
  };
  componentWillMount() {
    this.loadData();
    let param={
      page: this.state.page,
      pagesize: this.state.pagesize,
      name: this.state.name,
      bill_enum: this.state.bill_enum,
      bill_type:this.state.bill_type,
    }
    this.fetch(param);
  }
  fetch = (params = {}) => {
    this.setState({ loading: true });
     Workflow.getlist(params).then(data => {
        this.setState({
            loading: false,
            data:data.data,
            bill_enum:params.bill_enum,
            bill_type:params.bill_type,
            page: params.page,
            pagesize: params.pagesize,
            total: data.total,
        });
    });
  };
  handlesel = () => {
    let param={
      page: 1,
      pagesize: this.state.pagesize,
      name: this.state.name,
      bill_enum: this.state.bill_enum,
      bill_type:this.state.bill_type,
    }
    this.fetch(param);
  };
   handleTableChange = (pagination, filters, sorter) => {
    localStorage.setItem("workflowlistpagesize", pagination.pageSize);
    let param={
      page: pagination.current,
      pagesize: pagination.pageSize,
      name: this.state.name,
      bill_enum: this.state.bill_enum,
      bill_type:this.state.bill_type,
    }
    this.fetch(param);
  };
  handleCopy= record => {
    confirm({
      title: '确定复制审批流程?',
      icon: <WarningOutlined />,
      content: record.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        Workflow.copy({id:record.id,userid:currentUser.id}).then(()=>{
          notification.success("审批流程复制成功.");
          let param={
            page: 1,
            pagesize: this.state.pagesize,
            name: this.state.name,
            bill_enum: this.state.bill_enum,
            bill_type:this.state.bill_type,
          }
          this.fetch(param);
        }).catch(error => {
          notification.error(get(error, "response.data.message", "复制失败."));
        });
      },
    });
  };
  handleDelete = record => {
    confirm({
      title: '确定删除审批流程?',
      icon: <WarningOutlined />,
      content: record.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        Workflow.delete(record).then(()=>{
          notification.success("审批流程删除成功.");
          let param={
            page: 1,
            pagesize: this.state.pagesize,
            name: this.state.name,
            bill_enum: this.state.bill_enum,
            bill_type:this.state.bill_type,
          }
          this.fetch(param);
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
  loadData=()=> {
    let params={
      page: 1,
      pagesize: 100,
      code: '',
      name: '',
      userid: currentUser.id,
    }
    Tabletype.getlist(params).then(data => {
      const loop = (das, index) => {
        let items=[];
        das.forEach((item) => {
          item.icon= <SecurityScanTwoTone />;
          item.title=item.name;
          item.key=item.code+item.type
          if (item.children) {
            item.children= loop(item.children, index+1);
          }
          items.push(item);
        });
        return items;
      };
      let datas=loop(data.data,0);
      this.setState({
        loading: false,
        gData: datas,
        bill_enum:'',
        bill_type: '',
      });
    });
  }
  onSelect = (selectedKeys, e) => {
          let param={
            page: 1,
            pagesize: this.state.pagesize,
            name: this.state.name,
            bill_enum: e.node.code,
            bill_type: e.node.type,
          }
          this.fetch(param);
};
onDragEnter = info => {
    window.console.log(info);
  };
  render() {
      const paginationProps = {
            showSizeChanger: true,
            total: this.state.total, // 数据总数
            pageSize: parseInt(this.state.pagesize), // 每页条数
            current: parseInt(this.state.page), // 当前页码
            pageSizeOptions: ["10", "20", "30","100"],
            showTotal: ((total) => {
              return `共 ${total} 条`;
            }),
          };
        const listcolumns = [
      {
        title: '流程名称',
        key: 'name',
        dataIndex: 'name',
        render: (text, record) => (
          <Router  history={customHistory}>
            <Link to={`/workflow/new/${record.id}`}>{text}</Link>
           </Router>
        ),
      },
      {
        title: '单据名称',
        dataIndex: 'billname',
        key: 'billname',
      },
      {
        title: '部门名称',
        dataIndex: 'orgunitname',
        key: 'orgunitname',
      },
      {
        title: '状态',
        dataIndex: 'strstatus',
        key: 'strstatus',
      },
      {
        title: '操作',
         key: 'action',
        render: (text, record) => (
          <span>
            <a className="clickable" onClick={() => this.handleCopy(record)}>复制</a>
            <Divider type="vertical" />
             <a className="clickable" onClick={() => this.handleDelete(record)}>删除</a>
          </span>
        ),
      },
    ];
    return (
      <div>
      <ConfigProvider locale={zhCN}>
      <div className="container">
        <PageHeader title="审批流程列表"/>
      </div>
      <Row>
			  <Col span={5}>
            <Sider width={300} style={{ background: '#fff' }}>
              <Tree
                className="draggable-tree"
                draggable
                blockNode
                showIcon
                switcherIcon={<DownOutlined />}
                defaultExpandAll
                onDragEnter={this.onDragEnter}
                onSelect={this.onSelect}
                treeData={this.state.gData}
              />
            </Sider>
          </Col>
          <Col span={18}>
         <Form layout="horizontal" {...{labelCol: { span: 6 }, wrapperCol: { span: 12 },} }>
          <Row>
				  <Col span={8}>
            <Form.Item style={{ marginBottom: 5 }} label="流程名称">
              <Input
                value={this.state.name}
                onChange={e => this.setState({name:e.target.value})}
                placeholder="流程名称"
              />
						</Form.Item>
				  </Col>
          </Row>
          <Row>
				  <Col span={8}>
            <Button type="primary" >
                <i className="fa fa-plus m-r-5" />
                <a href="workflow/new/0" style={{color:"white"}}>新增</a>
            </Button>
				  </Col>
				  <Col span={8}>
          <Button type="primary" onClick={() => this.handlesel()} >
            <i className="fa fa-search m-r-5" />
            查询
          </Button>
				  </Col>
          </Row>
         </Form>
          <div>
              <Table rowKey='id'
                     columns={listcolumns}
                     dataSource={this.state.data}
                     pagination={paginationProps}
                     loading={this.state.loading}
                     onChange={this.handleTableChange}
              />
         </div>
         </Col>
         </Row>
    {/*</div>*/}
  </ConfigProvider>
  </div>
    );
  }
}

routes.register(
  "Workflow.List",
  routeWithUserSession({
    path: "/workflow",
    title: "我提交的审批流程",
    render: pageProps => <WorkFlowList {...pageProps}/>,
  })
);

